using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace Mes.质检管理.ProductCheck
{
    public partial class ProductCheckDetailForm : Form
    {
        private readonly int inspectionId;
        private readonly string passedInspectionNo;
        private readonly string passedInspectionDate;
        private const string DETAIL_URL = "/api/Inspection/GetDetailByInspectionId?InspectionId=";
        private const string PROCESS_URL = "/api/Inspection/GetProcessByInspectionId?InspectionId=";

        public ProductCheckDetailForm(int inspectionId)
        {
            this.inspectionId = inspectionId;
            InitializeComponent();
            // 隐藏供应商
            if (label3 != null) label3.Visible = false;
            if (lblSupplier != null) lblSupplier.Visible = false;
        }

        public ProductCheckDetailForm(int inspectionId, string inspectionNo, string inspectionDate)
        {
            this.inspectionId = inspectionId;
            this.passedInspectionNo = inspectionNo;
            this.passedInspectionDate = inspectionDate;
            InitializeComponent();
            // 隐藏供应商
            if (label3 != null) label3.Visible = false;
            if (lblSupplier != null) lblSupplier.Visible = false;
            // 反填基本信息（仅展示，不依赖接口）
            if (lblInspectionNo != null) lblInspectionNo.Text = passedInspectionNo ?? "-";
            if (lblInspectionDate != null) lblInspectionDate.Text = passedInspectionDate ?? "-";
        }

        protected override async void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                // 若通过无参构造进入，此处也尝试反填（保持稳健性）
                if (!string.IsNullOrEmpty(passedInspectionNo) && lblInspectionNo != null)
                {
                    lblInspectionNo.Text = passedInspectionNo;
                }
                if (!string.IsNullOrEmpty(passedInspectionDate) && lblInspectionDate != null)
                {
                    lblInspectionDate.Text = passedInspectionDate;
                }
                using (var client = new HttpClient())
                {
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(30);

                    // 发送GET请求获取详情数据（前半部分由 HttpClientHelper 封装）
                    var detailResponse = await client.GetAsync(HttpClientHelper.GetApiUrl("/api/Inspection/GetDetailByInspectionId") + $"?InspectionId={inspectionId}");
                    var processResponse = await client.GetAsync(HttpClientHelper.GetApiUrl("/api/Inspection/GetProcessByInspectionId") + $"?InspectionId={inspectionId}");

                    // 检查响应状态并获取数据
                    if (detailResponse.IsSuccessStatusCode && processResponse.IsSuccessStatusCode)
                    {
                        var detailJson = await detailResponse.Content.ReadAsStringAsync();
                        var processJson = await processResponse.Content.ReadAsStringAsync();

                        var detail = JsonConvert.DeserializeObject<ApiResult<InspectionDetailDto>>(detailJson);
                        var process = JsonConvert.DeserializeObject<ApiResult<ProcessDto>>(processJson);

                        if (detail != null && detail.data != null)
                        {
                            lblQty.Text = detail.data.InspectionQuantity.ToString();
                            lblQualified.Text = detail.data.QualifiedQuantity.ToString();
                            lblUnqualified.Text = detail.data.UnqualifiedQuantity.ToString();
                            lblInspector.Text = detail.data.Inspector;
                            lblRemarks.Text = detail.data.Remarks;
                            lblResult.Text = detail.data.InspectionResult;
                        }

                        if (process != null && process.data != null)
                        {
                            lblProductNo.Text = process.data.ProductNo;
                            lblProductName.Text = process.data.ProductName;
                            lblSpecification.Text = process.data.Specification;
                            lblLineNo.Text = process.data.ProductionLineNo;
                            lblRouteNo.Text = process.data.ProcessRouteNo;
                            lblRouteName.Text = process.data.ProcessRouteName;
                            lblStepNo.Text = process.data.ProcessStepNo;
                            lblStepName.Text = process.data.ProcessStepName;
                        }
                    }
                    else
                    {
                        // 处理错误响应
                        string detailError = detailResponse.IsSuccessStatusCode ? "" : await detailResponse.Content.ReadAsStringAsync();
                        string processError = processResponse.IsSuccessStatusCode ? "" : await processResponse.Content.ReadAsStringAsync();
                        MessageBox.Show($"加载详情失败：{detailError} {processError}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载详情失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    // 复用同命名空间下已有的 ApiResult<T>（定义在 ProductCheckShow.cs）

    public class InspectionDetailDto
    {
        public int InspectionQuantity { get; set; }
        public int QualifiedQuantity { get; set; }
        public int UnqualifiedQuantity { get; set; }
        public string Inspector { get; set; }
        public string Remarks { get; set; }
        public string InspectionResult { get; set; }
    }

    public class ProcessDto
    {
        public string ProductNo { get; set; }
        public string ProductName { get; set; }
        public string Specification { get; set; }
        public string ProductionLineNo { get; set; }
        public string ProcessRouteNo { get; set; }
        public string ProcessRouteName { get; set; }
        public string ProcessStepNo { get; set; }
        public string ProcessStepName { get; set; }
    }
}


